package get.newsdaily.adapters;

import get.newsdaily.R;
import get.newsdaily.model.RssItem;
import get.newsdaily.utils.variables;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ListNewsAdapter extends ArrayAdapter<RssItem> {
	private Context context;
	private List<RssItem> listItem;
	private int paper;
	private int layout;
private HashMap<String, Bitmap> bitMap = new HashMap<>();
	public ListNewsAdapter(Context context, int layout, int paper,
			List<RssItem> listItem) {
		super(context, layout, listItem);
		this.listItem = listItem;
		this.context = context;
		this.paper = paper;
		this.layout = layout;

	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		convertView = inflater.inflate(layout, parent, false);
		ImageView iv = (ImageView) convertView.findViewById(R.id.ivIcon);
		TextView tv = (TextView) convertView.findViewById(R.id.tvPaper);
		 iv.setImageResource(variables.ICONS[paper]);
	
		tv.setText(listItem.get(position).getTitle());
		if (listItem.get(position).getDescription() != null) {
		if(bitMap.get(listItem.get(position).getDescription())!=null) {
			iv.setImageBitmap(bitMap.get(listItem.get(position).getDescription()));
		}
		
		{new Thread((Runnable) new ListAsynTask(iv).execute(listItem.get(position).getDescription())).start();
			}
			} else {
			iv.setImageResource(variables.ICONS[paper]);
		}
		return convertView;
	}

	class ListAsynTask extends AsyncTask<String, Void, Bitmap> implements
			Runnable {
		String urldisplay;
		ImageView bmImage;
	

		public ListAsynTask(ImageView bmImage) {

			this.bmImage = bmImage;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			// if (this.dialog.isShowing()) {//tắt dialog
			// this.dialog.dismiss();
			//
			// }
		bitMap.put(urldisplay, result);
			 bmImage.setImageBitmap(result);
			
		}

		@Override
		protected Bitmap doInBackground(String... params) {
			//String 
			urldisplay = params[0];
			Bitmap mIcon11 = null;
			try {
				InputStream in = new java.net.URL(urldisplay).openStream();
				mIcon11 = BitmapFactory.decodeStream(in);
			} catch (Exception e) {
				Log.e("Error", e.getMessage());
				e.printStackTrace();
			}
			return mIcon11;

		}

		@Override
		public void run() {

		}

	}
}

